package web

import (
	"embed"
	"fmt"
	"lktx-dns/web/controller"
	"log"
	"net/http"
	"runtime/debug"
	"strconv"
)

//go:embed static
var content embed.FS

// 全局异常拦截器中间件
func recoveryMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "*")
		w.Header().Set("Access-Control-Allow-Credentials", "*")
		w.Header().Set("Access-Control-Allow-Headers", "*")
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}
		defer func() {
			if err := recover(); err != nil {
				// 捕获异常并记录日志
				log.Printf("服务器错误: %v\n栈情况: %s", err, string(debug.Stack()))
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusInternalServerError)
				fmt.Fprintf(w, `{"error": "服务器错误", "message": "%v"}`, err)
			}
		}()
		w.Header().Set("Content-Type", "application/json")
		next.ServeHTTP(w, r)
	})
}

func StartWebServer(port int) {
	mux := http.NewServeMux()
	mux.HandleFunc("/", controller.StaticController{Content: content}.Static)
	mux.HandleFunc("/user/login", controller.LoginController{}.LoginHandler)

	domainController := controller.DomainController{}
	mux.HandleFunc("/client/domain/list", domainController.GetDomainList)
	mux.HandleFunc("/client/domain/remove", domainController.RemoveDomain)
	mux.HandleFunc("/client/domain/add", domainController.Save)
	mux.HandleFunc("/client/domain/query", domainController.Query)

	proxyController := controller.ProxyController{}
	mux.HandleFunc("/client/proxy/list", proxyController.GetProxyList)
	mux.HandleFunc("/client/proxy/remove", proxyController.RemoveProxy)
	mux.HandleFunc("/client/proxy/add", proxyController.SaveProxy)
	mux.HandleFunc("/client/proxy/query", proxyController.QueryProxy)

	statisticsController := controller.StatisticsInfo{}
	mux.HandleFunc("/client/systemInfo", statisticsController.SystemInfoHandler)
	mux.HandleFunc("/client/statistics", statisticsController.StatisticsHandler)
	mux.HandleFunc("/client/statisticsGroup", statisticsController.StatisticsGroupHandler)
	mux.HandleFunc("/client/statisticsTypeTime", statisticsController.StatisticsTypeTimeHandler)

	caController := controller.CaInfo{}
	mux.HandleFunc("/client/caInfo", caController.CaHandler)

	muxWithRecovery := recoveryMiddleware(mux)
	log.Fatal(http.ListenAndServe(":"+strconv.Itoa(port), muxWithRecovery))
}
